import { PageContainer, ProCard, ProList } from '@ant-design/pro-components';
import React, { Key, useEffect, useState } from 'react';
import { Statistic } from 'antd';
import {
  getInterfaceTotalCondUsingGet,
  listInterfaceInfoByPageUsingPost,
} from '@/services/sutongapi-backend/interfaceInfoController';
import moment, { Duration } from 'moment';
import styles from './index.less';

const Index: React.FC = () => {
  const [expandedRowKeys, setExpandedRowKeys] = useState<readonly Key[]>([]);
  const [data, setData] = useState<API.InterfaceTotalVo>();
  const [timeDiff, setTimeDiff] = useState<Duration>(moment.duration(0));

  let intervalId: null | NodeJS.Timeout = null;
  const loadData = async () => {
    const res = await getInterfaceTotalCondUsingGet();
    setData(res.data);

    const updateTime = () => {
      const now = moment();
      const startTime = moment(res.data?.createWebsiteTime);

      const diff = moment.duration(now.diff(startTime));
      setTimeDiff(diff);
    };
    updateTime(); // 初始化时调用一次
    intervalId = setInterval(updateTime, 1000); // 每秒更新一次
  };

  useEffect(() => {
    loadData();
    // 清除定时器
    return () => clearInterval(Number(intervalId));
  }, []);

  return (
    <>
      <ProCard
        title="API开放平台"
        headStyle={{ textAlign: 'center' }}
        bodyStyle={{ fontSize: '15px' }}
        bordered
        direction="column"
        layout="center"
      >
        <div className={styles['title']}>高速稳定免费APi接口调用平台</div>
        <div className={styles['info']}>本站现共有{data?.total}个接口</div>
        <div className={styles['info']}>接口总调用{data?.totalCall}次</div>
        <div className={styles['runningTime']}>
          本站已稳定运行 {Math.floor(timeDiff.asDays())} 天 {timeDiff.hours()} 小时{' '}
          {timeDiff.minutes()} 分钟 {timeDiff.seconds()} 秒
        </div>
      </ProCard>

      <PageContainer header={{ title: '' }}>
        <ProList<API.InterfaceInfo>
          style={{ padding: 20 }}
          search={{}}
          size="large"
          pagination={{
            defaultPageSize: 10,
            showSizeChanger: true,
          }}
          metas={{
            title: {
              dataIndex: 'name',
              title: '名称',
            },
            subTitle: {
              dataIndex: 'name',
              search: false,
            },
            type: {
              search: false,
            },
            description: {
              dataIndex: 'description',
              search: false,
              render: (_, record) => {
                return <div style={{ marginTop: 10, fontSize: 13 }}>{record.description}</div>;
              },
            },
            content: {
              search: false,
              render: (_, record) => {
                return (
                  <div
                    style={{
                      flex: 1,
                      display: 'flex',
                      justifyContent: 'flex-end',
                    }}
                  >
                    <div
                      style={{
                        width: 200,
                      }}
                    >
                      <Statistic
                        title="调用次数"
                        value={112893}
                        valueStyle={{ fontSize: '15px' }}
                      />
                    </div>
                  </div>
                );
              },
            },
            actions: {
              search: false,
              render: (_, record) => {
                return [
                  <a key="detail" href={`/interfaceInfoDetail/${record.id}`}>
                    查看详情
                  </a>,
                  <a key="call" href={`/interfaceInfoCall/${record.id}`}>
                    在线调用
                  </a>,
                ];
              },
            },
          }}
          request={async (params) => {
            const res = await listInterfaceInfoByPageUsingPost({
              ...params,
            });
            return {
              data: res.data?.records || [],
              success: res.code === 0,
              total: res.data?.total || 0,
            };
          }}
          rowKey="id"
          headerTitle="首页"
          expandable={{
            expandedRowKeys,
            onExpandedRowsChange: setExpandedRowKeys,
          }}
        />
      </PageContainer>
    </>
  );
};

export default Index;
